package com.ttg.web.task.mctJob;

import com.ttg.common.enums.GrowTaskTypeEnum;
import com.ttg.common.exception.BaseException;
import com.ttg.web.redis.RedissonUtils;
import com.ttg.web.service.MctInfoService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobContext;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 根据客户活期存款更新成长值和积分
 */
@Slf4j
@Component
public class StartMctRatingCurrentDepositHandler {


    @Autowired
    private MctInfoService mctInfoService;

    @Autowired
    private RedissonUtils redissonUtils;

    @XxlJob("StartMctRatingCurrentDepositHandler")
    @Async
    public ReturnT<String> execute() {
        log.info("【MerchantJobTask startMctRatingCurrentDeposit 根据客户活期存款更新成长值和积分】 start");
        RLock rLock = null;
        try {
            rLock = redissonUtils.getRLock(GrowTaskTypeEnum.TYPE_PUBLIC.getValue());
            boolean flag = rLock.tryLock(5, 60 * 5, TimeUnit.SECONDS);
            if (flag) {
                mctInfoService.startMctRatingCurrentDeposit();
            }
        } catch (Exception e) {
            log.error("异常调度异常：{}",e.getMessage());
            XxlJobContext.getXxlJobContext().setHandleCode(ReturnT.FAIL_CODE);
            XxlJobContext.getXxlJobContext().setHandleMsg("执行异常，请联系管理员查询相关日志" + e.getMessage());
            throw new BaseException("异常调度异常",e.getLocalizedMessage());
        }finally {
            if (Objects.nonNull(rLock) && rLock.isLocked()) {
                rLock.unlock();
            }
        }
        log.info("【MerchantJobTask startMctRatingCurrentDeposit 根据客户活期存款更新成长值和积分】 end");
        return ReturnT.SUCCESS;
    }
}
